<template>
  <div class="login-page">
    <div class="login-container">
      <h2 class="title">template</h2>
      <h2 class="title">注册</h2>
      <el-form
        :model="form"
        :rules="rules"
        ref="formRef"
        label-width="80px"
        class="login-form"
      >
        <el-form-item label="头像" prop="avatar">
          <el-upload
            :action="uploadPath"
            :before-upload="beforeUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccessAdd"
            :on-error="handleAvatarErrorAdd"
            :headers="{ Authorization: getStorage('TOKEN') }"
            ref="upload"
          >
            <el-avatar
              :src="form.avatar || noAvatar"
              @click="handleAvatarClick"
            />
            <el-input v-model="form.avatar" type="hidden"></el-input>
          </el-upload>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="form.password"
            placeholder="请输入密码"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="form.sex">
            <el-radio value="男">男</el-radio>
            <el-radio value="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="form.age" :min="1" :max="120" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role" placeholder="请选择角色">
            <el-option label="管理员" value="ADMIN"></el-option>
            <el-option label="普通用户" value="USER"></el-option>
          </el-select>
        </el-form-item>
        <!-- 滑块验证码 -->
        <el-form-item v-if="isSlideEnabled" label="验证码" prop="slideVerify">
          <PuzzleCode
            v-model:complete="form.slideVerify"
            :canvas-width="300"
            :canvas-height="160"
            :slider-size="40"
            :border-radius="8"
            success-text="验证成功！"
            fail-text="验证失败，请重试"
            slider-text="请拖动滑块完成验证"
            @success="handleSlideSuccess"
            @fail="handleSlideFail"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="login-btn" @click="onSubmit">
            注册
          </el-button>
        </el-form-item>
      </el-form>
      <div class="footer">
        已有账号？
        <el-button @click="goToLogin">立即登录</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { register } from '@/api/User.js'
import { getStorage, setStorage } from '@/utils/storage.js'
import { ElMessage } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import useUserStore from '@/store/user.js'
import { getCurrentInstance, ref } from 'vue'
import noAvatar from '@/assets/no-avatar.png'
import PuzzleCode from '@/components/PuzzleCode.vue'

const userStore = useUserStore()
const router = useRouter()
const route = useRoute()
const { proxy } = getCurrentInstance()

const BASE_URL = import.meta.env.VITE_BASE_API
const uploadPath = BASE_URL + '/common/upload'

// 是否启用滑块验证
const isSlideEnabled = import.meta.env.VITE_REGISTER_SLIDE_ENABLED === 'true'

const form = ref({
  avatar: '',
  nickname: '',
  username: '',
  password: '',
  sex: '男',
  age: '',
  phone: '',
  email: ''
})

const rules = {
  avatar: [{ required: true, message: '请上传头像', trigger: 'blur' }],
  nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  sex: [{ required: true, message: '请选择性别', trigger: 'blur' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }]
}

// 滑块验证成功回调
const handleSlideSuccess = (x) => {
  form.value.slideVerify = true
  ElMessage.success('验证成功')
}

// 滑块验证失败回调
const handleSlideFail = (x) => {
  form.value.slideVerify = false
  ElMessage.warning('验证失败，请重试')
}

const onSubmit = () => {
  proxy.$refs.formRef.validate(valid => {
    if (valid) {
      // 如果启用了滑块验证但未通过验证，则提示用户
      if (isSlideEnabled && !form.value.slideVerify) {
        ElMessage.warning('请完成滑块验证')
        return
      }

      // 提交注册信息
      register(form.value).then(res => {
        if (res.code === 1) {
          ElMessage({
            message: '注册成功',
            type: 'success'
          })
          router.push({ path: '/login' })
        } else {
          // 注册失败时重置滑块验证
          if (isSlideEnabled) {
            proxy.$refs.formRef.clearValidate('slideVerify')
            form.value.slideVerify = false
          }
        }
      })
    }
  })
}

const handleAvatarClick = () => {
  proxy.$refs.upload.uploadFiles()
}

// 上传文件前的校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isImage) {
    ElMessage.error('上传文件只能是图片!')
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
  }
  return isImage && isLt2M
}

// 上传图片成功后的回调
const handleAvatarSuccessAdd = (res, file) => {
  form.value.avatar = file.response.data
}

// 上传图片失败后的回调
const handleAvatarErrorAdd = (err, file) => {
  if (err.toString().indexOf('401')) {
    ElMessage.error('请先登录!')
    router.push('/login')
  } else {
    ElMessage.error(err)
  }
}

const goToLogin = () => {
  router.push('/login')
}
</script>

<style scoped lang="scss">
.login-page {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-image: url('@/assets/images/login.jpeg');
  background-size: cover;
  background-position: center;
}

.login-container {
  width: 360px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}

.login-form {
  margin-top: 10px;
}

.login-btn {
  width: 100%;
}

.footer {
  margin-top: 20px;
  font-size: 14px;
  color: #666;
}

.register-link {
  color: #409eff;
  text-decoration: none;
}
</style>
